import time
import datetime
# import sched
import threading
import functools

defaultTimeStampFormat = '%Y-%m-%d-%H-%M-%S'
# _scheduler = sched.scheduler(time.time,time.sleep)


def get_cur_time_in_seconds():
    return time.time()


def get_cur_second_int():
    return int(time.time())


def get_cur_timeStamp(str_format=defaultTimeStampFormat):
    return datetime.datetime.now().strftime(str_format)


def get_timeStamp(_time, str_format=defaultTimeStampFormat):
    return datetime.datetime.fromtimestamp(_time).strftime(str_format)


def delay_func(delaySeconds, func, *args, **kw):
    # 原本这个写法似乎是阻塞的
    # return _scheduler.enter(delaySeconds,0,func,args,kw)
    threading.Timer(delaySeconds, func, *args, **kw).start()


def _loop_func(intervalSeconds, end_func, func, *args, **kw):
    '''intervalSeconds 表示时间间隔
    end_func 表示终止函数，该函数没有参数，返回bool值，如果为True，则终止
    func 表示要循环调用的函数，*args,**kw 表示它的参数
    '''
    def func_wrapper(*args, **kw):
        while not end_func():
            time.sleep(intervalSeconds)
            try:
                func(*args, **kw)
            except Exception as e:
                print(get_cur_timeStamp(), e)
        print("loop_func {} end".format(func.__name__))
    f_wrap = functools.partial(func_wrapper, *args, **kw)
    threading.Thread(target=f_wrap).start()

def loop_func(intervalSeconds, func, *args, **kw):
    _loop_func(intervalSeconds,lambda:False,func,*args,**kw)
